package com.zhou.base.components.bs.common.util;

import cn.hutool.core.util.StrUtil;
import com.zhou.base.components.bs.common.exception.base.BaseExceptionBuilder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author xianfeng
 * @date 2023/11/15 11:40
 */
public class DownloaFileUtil {

    public static boolean isBrowser() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null && requestAttributes.getRequest() != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            String userAgent = request.getHeader("User-Agent");
            if (StrUtil.isNotEmpty(userAgent) && (userAgent.contains("Mozilla") || userAgent.contains("Chrome"))) {
                // 是浏览器访问
                return true;
            }
        }
        return false;
    }

    public static void downloadExcel(HttpServletResponse response, String fileName,
                                     Runnable runnable) {
        //判断文件后缀
        if (!StrUtil.endWith(fileName, ".xlsx")) {
            fileName += ".xlsx";
        }
        //判断是否是浏览器，要进行encode
        if (isBrowser()) {
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw BaseExceptionBuilder.with(e);
            }
        }
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        runnable.run();
    }

}
